package cn.congine.wizarpos.mall.action;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.congine.wizarpos.mall.model.ErpProduct;
import cn.congine.wizarpos.mall.model.ErpProductCategory;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderBindingInput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderBindingOutput;
import cn.congine.wizarpos.mall.model.open.Merchandise;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncInput;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncOutput;
import cn.congine.wizarpos.mall.model.open.MerchantDef;
import cn.congine.wizarpos.mall.model.open.ProductCategorySyncInput;
import cn.congine.wizarpos.mall.model.open.ProductCategorySyncOutput;
import cn.congine.wizarpos.mall.model.open.TicketUseInput;
import cn.congine.wizarpos.mall.model.open.TicketUseOutput;
import cn.congine.wizarpos.mall.model.open.WxSaleOrderQueryInput;
import cn.congine.wizarpos.mall.model.open.WxSaleOrderQueryOutput;
import cn.congine.wizarpos.mall.service.impl.WPosHttpClient;
import cn.congine.wizarpos.mall.service.impl.WizarposOpenRestClient;
import cn.congine.wizarpos.mall.service.impl.WxHttpClient;
import cn.congine.wizarpos.mall.utils.Function;
import cn.congine.wizarpos.mall.utils.SysConstants;
import cn.congine.wizarpos.mall.utils.Utils;
import cn.congine.wizarpos.mall.vo.ProductView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping(value = "/takeout")
public class TakeoutAction {
	private final Log log = LogFactory.getLog(getClass());

	@Autowired
	private WPosHttpClient wPosHttpClient;

	@Autowired
	private WxHttpClient wxHttpClient;

	@Autowired
	private WizarposOpenRestClient wizarposOpenRestClient;	

	@Resource(name = "messageSource")
	private MessageSource messageSource;

	/**
	 * 
	 * @param tableId
	 * @param openId
	 * @param mid
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/submit", method = RequestMethod.POST)
	public @ResponseBody String submit(
			@RequestParam(value = "token", required = true) String token,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "sum", required = true) String sum,
			@RequestParam(value = "customer", required = true) String customer,
			@RequestParam(value = "address", required = true) String address,
			@RequestParam(value = "tel", required = true) String tel,
			@RequestParam(value = "orderDetail", required = true) String orderDetail,
			@RequestParam(value = "remark", required = true) String remark,//add xudongdong
			@RequestParam(value = "nonceStr", required = true) String nonceStr,
			@RequestParam(value = "ticketInfoIds", required = true) String ticketInfoIds,
			@RequestParam(value = "payType", required = true) String payType,
			HttpServletRequest httpRequest) throws UnsupportedEncodingException {
		
		System.out.println("");
		System.out.println("-----/submitmenu----token:" + token);
		System.out.println("");
		System.out.println("");
		System.out.println("-----/submitmenu----session:" + httpRequest.getSession().getAttribute(
				SysConstants.SESSION_TOKEN));
		
		String cardNo = null;
		int balance = 0;
		JSONObject result = wPosHttpClient.getMerchantCardByOpenId(openId, mid);
		int errcode = result.getIntValue("code");
		if (errcode == 0) {
			JSONObject cardVip = result.getJSONObject("result");
			// 获取对应的会员卡卡号
			cardNo = cardVip.getString("cardNo");
			balance= cardVip.getIntValue("balance");
		}
		
		if ("1".equals(payType) && balance < Double.valueOf(sum)*100) {
			return "-1";
		}
		
		if(Utils.isRepeatSubmit(httpRequest, token)) {
			return "1";
		}
		
		JSONObject json = new JSONObject();
		json.put("mid", mid);
		json.put("takeoutCustomer", customer);
		json.put("takeoutAddr", address);
		json.put("takeoutTel", tel);
		json.put("orderType", "3");//餐饮类型外卖
		json.put("orderSource", "2");//微信订单
		json.put("amount", sum);
		json.put("orderDetail", JSON.parseArray(orderDetail));
		json.put("print", true);
		json.put("remark", remark);//订单备注 add xudongdong
		
		JSONObject respJson = null;
		try {
			respJson = wPosHttpClient.postOpen("/catering/saleorder/submit",
					json);
		} catch (Exception e) {
			log.error("呼叫开放平台出错，外卖点餐失败。");
			return "0";
		}

		String code = respJson.getString("code");
		if ("0".equals(code) || "60032".equals(code)) {
			System.out.println("");
			System.out.println("-----/submitmenu--success--code:"+code);
			System.out.println("");
			
			String orderId = respJson.getJSONObject("result").getString(
					"orderId");

			// 记录绑定信息
			CateringSaleOrderBindingInput input = new CateringSaleOrderBindingInput();
			input.setMid(mid);
			input.setOpenId(openId);
			input.setSaleOrderId(orderId);
			CateringSaleOrderBindingOutput ouptut = (CateringSaleOrderBindingOutput) wizarposOpenRestClient.post(input, "/catering/saleorder/binding", CateringSaleOrderBindingOutput.class);			

			if ("1".equals(payType)) {
				JSONObject param = new JSONObject();
				param.put("mid", mid);
				param.put("orderId", orderId);
				param.put("amount", sum);
				param.put("ticketInfoIds", JSON.parseArray(ticketInfoIds));
				param.put("cardNo", cardNo);
				param.put("print", true);
				
				JSONObject orderJson = null;
				try {
					orderJson = wPosHttpClient.postOpen("/catering/memberCardPay",
							param);
				} catch (Exception e) {
					// 消息推送失败
					log.error("餐饮订单支付失败，单号：" + orderId);
					return "-2";
				}
				
				if ("0".equals(orderJson.getString("code"))) {
					return orderId;
				} else {
					return "-2";
				}
			} else {
				return orderId;
			}
			
		} else {
			System.out.println("");
			System.out.println("-----/submitmenu--fail--code:" + code);
			System.out.println("");
			return "0";
		}
	}
	

	/**
	 * 准别点单
	 * 
	 * @param mid
	 * @param openId
	 * @param orderId
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/order")
	public ModelAndView order(
			@RequestParam(value = "sum", required = true) String sum,
			@RequestParam(value = "cardId", required = true) String cardId,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "orderDetail", required = true) String orderDetail,
			HttpServletRequest httpRequest) throws UnsupportedEncodingException {

		JSONArray detailArray = JSON
				.parseArray(orderDetail);
		List<ProductView> list = new ArrayList<ProductView>();
		for (int i = 0; i < detailArray.size(); i++) {
			JSONObject detail = detailArray.getJSONObject(i);
			ProductView pv = new ProductView();
			pv.setId(detail.getString("id"));
			pv.setName(URLDecoder.decode(detail.getString("name"), "UTF-8"));
			pv.setPrice(detail.getString("price"));
			pv.setNum(detail.getInteger("qty"));
			pv.setCode(detail.getString("code"));
			list.add(pv);
		}
		JSONArray tickets = null;
		if (cardId != null) {
			JSONObject ticketJson = wPosHttpClient.getCashTickets(openId, mid);
			if (ticketJson.getIntValue("code") == 0) {
				tickets = ticketJson.getJSONArray("result");//代金券
				for (int i = 0; i < tickets.size(); i++) {
					JSONObject obj = tickets.getJSONObject(i);
					obj.put("balance", Utils.formatAmount(obj.getString("balance")));			
				}
			}
		}
		
		Utils.setSessionToken(httpRequest);

		return new ModelAndView("takeout/order").addObject("products", list)
				.addObject("sum", sum).addObject("cardId", cardId).addObject("cashList", tickets)
				.addObject("openId", openId).addObject("mid", mid);
	}

	/**
	 * 订单详情
	 * 
	 * @param mid
	 * @param openId
	 * @param orderId
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/orderinfo")
	public ModelAndView orderInfo(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid)
			throws UnsupportedEncodingException {
		JSONObject json = new JSONObject();
		json.put("mid", mid);
		json.put("orderId", orderId);
		String OrderNo = null;
		WxSaleOrderQueryInput input = new WxSaleOrderQueryInput();
		input.setOrderId(orderId);
		WxSaleOrderQueryOutput output = (WxSaleOrderQueryOutput) wizarposOpenRestClient.post(input, "/wxshop/wxSaleOrderQuery", WxSaleOrderQueryOutput.class);
		if (output == null) {
			log.error("请求开放平台销售订单查询接口失败");
			return new ModelAndView("error").addObject("err_message", "系统错误。");			
		} else if ("0".equals(output.getCode())) {//0操作成功
			OrderNo = Function.getShowWxOrderNo(output.getResult().getOrderNo());
		} else if ("60020".equals(output.getCode())) {//60020非法订单编号
			return new ModelAndView("error").addObject("err_message",
					"系统错误，订单不存在");
		} else {//其它code码
			log.error("orderId: " + orderId);
			log.error("code: " + output.getCode() + "message: " + output.getMessage());
			return new ModelAndView("error").addObject("err_message", "系统错误。");			
		}
		JSONObject respJson = null;
		try {
			respJson = wPosHttpClient.postOpen("/catering/saleorder/query",
					json);
		} catch (Exception e) {
			log.error("餐饮订单查询失败，单号：" + orderId);
			return new ModelAndView("error").addObject("err_message", "系统错误。");
		}
		
		String code = respJson.getString("code");
		if ("0".equals(code)) {
			JSONObject orderInfo = respJson.getJSONObject("result");
			String payStatus = orderInfo.getString("payStatus");
			//若未填写订单备注，则页面显示无
			if (StringUtils.isEmpty(respJson.getJSONObject("result").getString("remark"))) {
				respJson.getJSONObject("result").put("remark", "无");
			}
			
			if ("0".equals(payStatus)) {
				JSONObject result = wPosHttpClient.getMerchantCardByOpenId(openId, mid);
				int errcode = result.getIntValue("code");
				String cardId = null;
				com.alibaba.fastjson.JSONArray tickets = null;
				if (errcode == 0) {
					JSONObject cardVip = result.getJSONObject("result");
					// 获取对应的会员卡卡号
					cardId = cardVip.getString("id");
					if (cardId != null) {
						JSONObject ticketJson = wPosHttpClient.getCashTickets(openId, mid);
						if (ticketJson.getIntValue("code") == 0) {
							tickets = ticketJson.getJSONArray("result");//代金券
							for (int i = 0; i < tickets.size(); i++) {
								JSONObject obj = tickets.getJSONObject(i);
								obj.put("balance", Utils.formatAmount(obj.getString("balance")));			
							}
						}
					}
				}
				
				return new ModelAndView("takeout/orderinfo").addObject("mid", mid)
						.addObject("openId", openId).addObject("orderId", orderId)
						.addObject("OrderNo", OrderNo)
						.addObject("cardId", cardId).addObject("cashList", tickets)
						.addObject("order", respJson.getJSONObject("result"));
			}
			return new ModelAndView("takeout/orderinfo").addObject("mid", mid)
					.addObject("openId", openId).addObject("orderId", orderId)
					.addObject("OrderNo", OrderNo)
					.addObject("order", respJson.getJSONObject("result"));
		} else {
			return new ModelAndView("error").addObject("err_message",
					respJson.getString("message"));
		}
	}


	/**
	 * 进入主菜单
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 */
	@RequestMapping(value = "/tomenu", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView toMenu(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "pageIndex", required = false) Integer pageIndex) {
		if(pageIndex == null) {
			pageIndex = 1;
		}
		
		ProductCategorySyncInput productCategorySyncInput = new ProductCategorySyncInput();
		productCategorySyncInput.setMid(mid);		
		ProductCategorySyncOutput productCategorySyncOutput = (ProductCategorySyncOutput) wizarposOpenRestClient.post(productCategorySyncInput, "/product/category", ProductCategorySyncOutput.class);
		
		List<ErpProductCategory>  categoryList = productCategorySyncOutput.getResult();	
		
		Map<String, Object> products = new HashMap<String, Object>();
		for (ErpProductCategory category : categoryList) {
			String categoryId = category.getId();
			String categoryCode = category.getCode();
			
			MerchandiseSyncInput merchandiseSyncInput = new MerchandiseSyncInput();
			merchandiseSyncInput.setMid(mid);
			merchandiseSyncInput.setCategoryId(categoryId);
			merchandiseSyncInput.setPageNo(pageIndex.toString());
			MerchandiseSyncOutput merchandiseSyncOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(merchandiseSyncInput, "/product/merchandise", MerchandiseSyncOutput.class);					
			
			List<Merchandise>  productListTemp = merchandiseSyncOutput.getResult();
			List<ErpProduct> productList = new ArrayList<ErpProduct>();			
			// 处理价格分-元，图片路径
			for (Merchandise prt : productListTemp) {
				ErpProduct ep = new ErpProduct();				
				ep.setId(prt.getProductId());
				ep.setCode(prt.getCode());
				ep.setName(prt.getName());				
				ep.setPrice(prt.getPrice());				
				ep.setShowMemPrice(prt.getMemberPrice());
				if ("".equals(prt.getPicUrl())) {
					ep.setPicUrl(SysConstants.DEFAULT_PICTURE);
				} else {
					ep.setPicUrl(Function.dealGridPicUrl(prt.getPicUrl(), 150, 150));
				}
				productList.add(ep);
			}
			// 迭代此分类下所有产品
			// getproductsUnderCategory(mid, categoryId, productList);

			products.put("topten" + categoryCode, productList);
		}
		JSONObject json = wPosHttpClient.getMerchantCardByOpenId(openId, mid);
		int code = json.getIntValue("code");
		String cardId = null;
		if (code == 0) {
			JSONObject cardVip = json.getJSONObject("result");
			// 获取对应的会员卡卡号
			cardId = cardVip.getString("id");
		}
		
		return new ModelAndView("takeout/menu")
				.addObject("categoryList", categoryList)
				.addObject("products", products).addObject("mid", mid)
				.addObject("cardId", cardId)
				.addObject("openId", openId);
	}
	
	/**
	 * 支付成功页面
	 * 
	 * @param orderId
	 * @param openId
	 * @param mid
	 * @return
	 */
	@RequestMapping(value = "/orderOk")
	@ResponseBody
	public ModelAndView orderOk(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid, 
			@RequestParam(value = "ticketInfoIds", required = false) String ticketInfoIds) {
			
			if (!StringUtils.isEmpty(ticketInfoIds)) { // 微信支付完成，用代金券
				TicketUseInput input = new TicketUseInput();
				input.setMid(mid);
				input.setOpenId(openId);
				input.setOrderId(orderId);
				input.setTicketInfoId(Arrays.asList(ticketInfoIds.split(",")));
				TicketUseOutput output = (TicketUseOutput) wizarposOpenRestClient.post(input, "/catering/ticket/use", TicketUseOutput.class);					
				if (output == null) {
					log.debug("微信支付完成，用代金券异常:" + ticketInfoIds);
				} else if (!SysConstants.OPEN_SUCCESS.equals(output.getCode())) {
					log.debug("微信支付完成，用代金券异常：" + output.getMessage() +", ticketInfoIds = "+ticketInfoIds);
				} 
			}
			return new ModelAndView("takeout/orderok")
					.addObject("mid", mid)
					.addObject("openId", openId).addObject("orderId", orderId);
	}

}
